﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using Cashier.DataEntry;
using Cashier;
using Cashier.PrintingControls;
using System.IO;
using System.Threading;
using System.Drawing.Printing;
namespace Cashier
{
    public partial class cashier_form : Form
    {
        #region Local Variables
        private Dictionary<string, string> dictVipCodes = new Dictionary<string, string>();
        private Dictionary<string, string> dicPhoneList = new Dictionary<string, string>();
        private Dictionary<int, OrderDetailsEntry> ordersList = new Dictionary<int, OrderDetailsEntry>();
        private List<string> VertTable = new List<string>();
        private Boolean addaction_cancle = false;
        private OrderDetailsEntry CurrentODE = new OrderDetailsEntry();
        private string dongia_before_edit;
        private int current_table_index;
        private float VAT = 0f;
        private DatabaseServices DBServices = new DatabaseServices();
        private bool is_vip = false;
        private int DelayTime = 30000;
        private bool lock_cname = false;
        private bool lock_ccode = false;
        private bool need_get_member_info{
            get
            {
                if (txt_Cashier_VIPCode.Text == "" && txt_Cashier_VIPName.Text != "")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        #endregion End of Local Variables
        private int current_point = 0;
        #region Readonly Fields

        /// <summary>
        /// Get the totals from DGV_OrderDetails
        /// </summary>
        private float Totals
        {
            get
            {
                float total = 0f;
                foreach (DataGridViewRow row in DGV_OrderDetails.Rows)
                {
                    if (row.Cells["clThanhTien"].Value != null && row.Cells["clThanhTien"].Value.ToString() !="")
                        total += float.Parse(row.Cells["clThanhTien"].Value.ToString());
                }
                return total;
            }
        }

        /// <summary>
        /// Get the Discount Percents value
        /// </summary>
        private float DiscountPercents
        {
            get
            {
                return float.Parse(txt_Cashier_DiscountPercent.Text);
            }
        }

        private string ListItemHTMLString
        {
            get
            {
                string result = "";
                string itemTemplate = "";
               
                List<int> step_over = new List<int>();
                foreach (DataGridViewRow row in DGV_OrderDetails.Rows)
                {                  
                    if (row.Index < DGV_OrderDetails.Rows.Count - 1)
                    {
                        bool isInList = step_over.IndexOf(row.Index) != -1;
                        if (!isInList)
                        {
                            //// Process template
                            string itemName = "", quantity = "", price = "";
                            if (row.Cells["clTenMon"].Value != null && row.Cells["clTenMon"].Value.ToString() != "")
                                itemName = row.Cells["clTenMon"].Value.ToString();
                            if (row.Cells["clSoLuong"].Value != null && row.Cells["clSoLuong"].Value.ToString() != "")
                                quantity = row.Cells["clSoLuong"].Value.ToString();
                            if (row.Cells["clThanhTien"].Value != null && row.Cells["clThanhTien"].Value.ToString() != "")
                                price = float.Parse(row.Cells["clThanhTien"].Value.ToString(), NumberStyles.Currency).ToString("0,0");

                            //sumery the quantity of each item
                            for (int i = row.Index + 1; i < DGV_OrderDetails.Rows.Count - 1; i++)
                            {
                                if (itemName == DGV_OrderDetails[1, i].Value.ToString())
                                {
                                    float _temp_price = 0;
                                    quantity = (int.Parse(quantity) + int.Parse(DGV_OrderDetails[3, i].Value.ToString())).ToString();
                                    _temp_price += float.Parse(DGV_OrderDetails[5, i].Value.ToString());
                                    // DGV_OrderDetails.Rows.RemoveAt(i);
                                    price = (float.Parse(price) + _temp_price).ToString("0,0"); ;

                                    step_over.Add(i);

                                }
                            }

                            itemTemplate = string.Format("<li><p class=\"item_name\">{0}</p><p class=\"quantity\">{1}</p><p class=\"price\">{2}</p></li>", itemName, quantity, price);

                            // Save item to list
                            result += itemTemplate;
                        }
                    }
                }
                return result;
            }
        }        

        /// <summary>
        /// Print Template for Bill
        /// </summary>
        private string PrintBillTemplate {

            get {
                return File.ReadAllText(Application.StartupPath + @"/printTemp/billTemplate.html");
            }
        }

        private int SelectedTableId
        {
            get
            {
                int selectedTableId = int.Parse(DGV_table.SelectedRows[0].Cells[0].Value.ToString());
                return selectedTableId;
            }
        }
        /// <summary>
        /// Check a string is Number or not
        /// </summary>
        private bool isStringNumber(string txt)
        {
            if (txt == null || txt == "")
                return false;
            foreach (char c in txt)
            {
                if (!char.IsNumber(c))
                    return false;
            }
            return true;
        }

        #endregion End of Readonly Fields

        #region Form constructor

        public cashier_form()
        {
            InitializeComponent();
            using (DatabaseServices service = new DatabaseServices())
            {
                combo_Cashier_PhucVu.Items.AddRange(service.GetListEmplogyeeNamesByType("Waiter").ToArray());
                service.FillDataToGrid("Select * from tables", DGV_table);
                //dictDiscountByVIPCodes = service.GetDiscountDict();
                dictVipCodes = service.GetVIPCodes();
                dicPhoneList = service.GetPhoneList();
                foreach (KeyValuePair<string, string> vipCode in dictVipCodes)
                {
                    this.txt_Cashier_VIPCode.AutoCompleteCustomSource.Add(vipCode.Key.ToString());
                    this.txt_Cashier_VIPName.AutoCompleteCustomSource.Add(vipCode.Value.ToString());
                }
                foreach (KeyValuePair<string, string> phone in dicPhoneList)
                {
                    this.text_PhoneNum.AutoCompleteCustomSource.Add(phone.Key.ToString());
                }
            }
        }

        #endregion

        #region Events - User actions

        //form closing
        private void cashier_form_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("If you close this window, all data will be lose. Are you sure to continue close this window ?", "Close ?",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }
        
        //form closed
        private void cashier_form_FormClosed(object sender, FormClosedEventArgs e)
        {
            new list_form().Show();
        }

        private void txt_SearchTable_KeyDown(object sender, KeyEventArgs e)
        {
           if (e.KeyCode == Keys.Enter) {

                TimPhucVu();
            }
        }

        //edit order cell
        private void DGV_OrderDetails_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                #region Column ID
                object itemIdSubmited = DGV_OrderDetails.Rows[e.RowIndex].Cells[0].Value;
                if (itemIdSubmited != null)
                {
                    string strItemId = itemIdSubmited.ToString();
                    if (strItemId == "/")
                    {
                        // construct the new Windows Form object
                        items_form fSender = new items_form();

                        // setup function to transfer the object
                        fSender.Send = new items_form.SendItemEntry(FillRecievedData);

                        // show sender form
                        fSender.Show();
                    }
                    else
                    {
                        using (DatabaseServices service = new DatabaseServices())
                        {
                            int _outId;
                            int id = int.TryParse(strItemId, out _outId) ? _outId : -1;
                            ItemEntry item = service.GetItem(id);
                            if (item != null)
                            {
                                bool isDuplicate = false;
                                int UpdateNeededRowIndex = -1;
                                int oldQuantity = 0;
                                for (int i = 0; i < DGV_OrderDetails.Rows.Count - 2; i++)
                                {
                                    if (DGV_OrderDetails.Rows[i].Cells[0].Value.ToString() == strItemId && DGV_OrderDetails.Rows[i].Cells[0].Value!=null)
                                    {
                                        
                                        isDuplicate = true;
                                        UpdateNeededRowIndex = i;
                                        oldQuantity = int.Parse(DGV_OrderDetails.Rows[i].Cells["clSoLuong"].Value.ToString());
                                        break;
                                    }
                                }
                                //if (isDuplicate)
                                //{
                                //    //TODO: Update the row which duplicated and remove the rowindex RowsCount - 2
                                //    if (UpdateNeededRowIndex >= 0)
                                //    {
                                //        DGV_OrderDetails.Rows[UpdateNeededRowIndex].Cells["clSoLuong"].Value = oldQuantity + 1;

                                //        float dongia = float.Parse(DGV_OrderDetails.Rows[UpdateNeededRowIndex].Cells["clDonGia"].Value.ToString());
                                //        DGV_OrderDetails.Rows[UpdateNeededRowIndex].Cells["clThanhTien"].Value = dongia * (oldQuantity + 1);
                                //        //DGV_OrderDetails.Rows.RemoveAt(e.RowIndex);
                                //        for (int i = 0; i < DGV_OrderDetails.ColumnCount - 1; i++)
                                //        {
                                //            DGV_OrderDetails.Rows[e.RowIndex].Cells[i].Value = "";
                                            
                                            
                                           
                                //        }
                                //        addaction_cancle = true;
                                //        /*for (int i = 0; i < DGV_OrderDetails.RowCount - 1; i++)
                                //        {
                                //            if (DGV_OrderDetails.Rows[i].Cells["clMaMon"].Value == "")
                                //            {
                                //                DGV_OrderDetails.Rows.RemoveAt(i);
                                //                DGV_OrderDetails.Rows.Add();
                                //            }
                                //        }*/
                                //        DGV_OrderDetails.Rows[DGV_OrderDetails.Rows.Count - 2].Selected = true;
                                        
                                //    }
                                //    isDuplicate = false;
                                //}
                                if (!isDuplicate)
                                {
                                    DGV_OrderDetails.Rows[e.RowIndex].SetValues(new object[] { item.ID, item.Name, item.Unit, "1", item.Price, (float)item.Price });
                                    DGV_OrderDetails.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
                                }
                                
                            }
                            else
                            {
                                try
                                {
                                    if (MessageBox.Show("This item is not exists. Do you want to remove it ?", "Not found!", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                                        DGV_OrderDetails.Rows.RemoveAt(e.RowIndex);
                                    else
                                        DGV_OrderDetails.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
                                }
                                catch { }

                            }
                            
                        }
                    }
                }
                #endregion
            }
            else if (e.ColumnIndex == 1)
            {
                #region ColumnItemName
                object itemIdSubmited = DGV_OrderDetails.Rows[e.RowIndex].Cells[1].Value;
                if (itemIdSubmited != null)
                {
                    string strItemName = itemIdSubmited.ToString();
                    if (strItemName == "/")
                    {
                        // construct the new Windows Form object
                        items_form fSender = new items_form();

                        // setup function to transfer the object
                        fSender.Send = new items_form.SendItemEntry(FillRecievedData);

                        // show sender form
                        fSender.Show();
                    }
                    else
                    {
                        using (DatabaseServices service = new DatabaseServices())
                        {
                            ItemEntry item = null;
                            if (service.GetItemsByName(strItemName).Count > 0)
                                item = service.GetItemsByName(strItemName).First();
                            if (item != null)
                            {
                                DGV_OrderDetails.Rows[e.RowIndex].SetValues(new object[] { item.ID, item.Name, item.Unit, "1", item.Price, item.Price });
                                DGV_OrderDetails.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
                                //DGV_OrderDetails.Rows[DGV_OrderDetails.CurrentRow.Index].Cells[3].Selected = true;
                            }
                            else
                            {
                                    DGV_OrderDetails.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
                            }
                        }
                    }
                }
                #endregion
            }
            //quan move to tb_TextChanged event
            /*
            else if (e.ColumnIndex == 3)
            {
                #region column so luong
                if (DGV_OrderDetails.Rows[e.RowIndex].Cells[0].Value == null)
                {
                    addaction_cancle = true;
                    return;

                }
                 object itemIdSubmited = DGV_OrderDetails.Rows[e.RowIndex].Cells[1].Value;
                 string soluong = DGV_OrderDetails.Rows[e.RowIndex].Cells[3].Value.ToString();
                 string dongia = DGV_OrderDetails.Rows[e.RowIndex].Cells[4].Value.ToString();
                 float _fSoluong = float.TryParse(soluong, out _fSoluong) ? _fSoluong : -1f;
                 float _fdongia = float.TryParse(dongia, out _fdongia) ? _fdongia : -1f;
                
                if (itemIdSubmited != null)
                 {
                     if (_fSoluong == -1)
                     {
                         MessageBox.Show("Invalid number.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                         soluong = rowValuesToEdit[3];
                         dongia = rowValuesToEdit[4];
                         _fSoluong = float.Parse(rowValuesToEdit[3]);
                     }
                     string strItemName = itemIdSubmited.ToString();
                     using (DatabaseServices service = new DatabaseServices())
                     {
                         ItemEntry item = null;
                         if (service.GetItemsByName(strItemName).Count > 0)
                             item = service.GetItemsByName(strItemName).First();
                         if (item != null)
                             DGV_OrderDetails.Rows[e.RowIndex].SetValues(new object[] { item.ID, item.Name, item.Unit, soluong, _fdongia, _fdongia * _fSoluong });
                         
                     }
                 }
                #endregion
            }
             * */
            else if (e.ColumnIndex == 4)
            {
                #region column Don Gia
                object itemIdSubmited = DGV_OrderDetails.Rows[e.RowIndex].Cells[1].Value;
                string soluong = DGV_OrderDetails.Rows[e.RowIndex].Cells[3].Value.ToString();
                string dongia = DGV_OrderDetails.Rows[e.RowIndex].Cells[4].Value.ToString();
                float _fdongia = float.TryParse(dongia, out _fdongia) ? _fdongia : -1f;
                if (itemIdSubmited != null)
                {
                    if (_fdongia == -1)
                    {
                        MessageBox.Show("Invalid number.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        dongia = rowValuesToEdit[4];
                        _fdongia = float.Parse(rowValuesToEdit[3]);
                    }
                    string strItemName = itemIdSubmited.ToString();
                    using (DatabaseServices service = new DatabaseServices())
                    {
                        ItemEntry item = null;
                        if (service.GetItemsByName(strItemName).Count > 0)
                            item = service.GetItemsByName(strItemName).First();
                        if (item != null)
                            DGV_OrderDetails.Rows[e.RowIndex].SetValues(new object[] { item.ID, item.Name, item.Unit, soluong, _fdongia, _fdongia * float.Parse(soluong) });

                    }
                }
                #endregion
            }
        }

        private List<string> rowValuesToEdit;
        /// <summary>
        /// Back up data before edit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DGV_OrderDetails_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                dongia_before_edit = DGV_OrderDetails.Rows[e.RowIndex].Cells[4].Value.ToString();
                rowValuesToEdit = new List<string>();
                foreach (DataGridViewCell cell in DGV_OrderDetails.Rows[e.RowIndex].Cells)
                {
                    if (e.RowIndex < DGV_OrderDetails.Rows.Count - 1)
                    {
                        rowValuesToEdit.Add(cell.Value.ToString());
                    }
                }
            }
            catch { }
        }
        private void DGV_OrderDetails_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            AutoCompleteStringCollection itemIdSource = new AutoCompleteStringCollection();
            AutoCompleteStringCollection itemNameSource = new AutoCompleteStringCollection();
            using (DatabaseServices service = new DatabaseServices())
            {
                itemIdSource.AddRange(service.GetListItemIds().ToArray());
                itemNameSource.AddRange(service.GetListItemNames().ToArray());
            }
            if (e.Control is DataGridViewTextBoxEditingControl)
            {
                var tec = (e.Control as DataGridViewTextBoxEditingControl);
                tec.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                tec.AutoCompleteSource = AutoCompleteSource.CustomSource;
                switch (DGV_OrderDetails.CurrentCell.ColumnIndex)
                {
                    case 0:
                        tec.AutoCompleteCustomSource = itemIdSource;
                        break;
                    case 1:
                        tec.AutoCompleteCustomSource = itemNameSource;
                        break;
                    case 3:
                        TextBox tb = (TextBox)e.Control;
                        tb.TextChanged += tb_TextChanged;
                        break;
                    default:
                        tec.AutoCompleteMode = AutoCompleteMode.None;
                        break;
                }
            }
        }

        void tb_TextChanged(object sender, EventArgs e)
        {
            string number = ((TextBox)sender).Text;
            //if (isStringNumber(number))
            {
                #region column so luong
                if (DGV_OrderDetails.CurrentRow.Cells[0].Value == null)
                {
                    addaction_cancle = true;
                    return;

                }
                object itemIdSubmited = DGV_OrderDetails.CurrentRow.Cells[1].Value;
                string soluong = number;
                string dongia = DGV_OrderDetails.CurrentRow.Cells[4].Value.ToString();
                float _fSoluong = float.TryParse(soluong, out _fSoluong) ? _fSoluong : -1f;
                float _fdongia = float.TryParse(dongia, out _fdongia) ? _fdongia : -1f;

                if (itemIdSubmited != null)
                {
                    if (_fSoluong == -1)
                    {
                        MessageBox.Show("Invalid number.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        soluong = rowValuesToEdit[3];
                        dongia = rowValuesToEdit[4];
                        _fSoluong = float.Parse(rowValuesToEdit[3]);
                    }
                    string strItemName = itemIdSubmited.ToString();
                    using (DatabaseServices service = new DatabaseServices())
                    {
                        ItemEntry item = null;
                        if (service.GetItemsByName(strItemName).Count > 0)
                            item = service.GetItemsByName(strItemName).First();
                        if (item != null)
                            DGV_OrderDetails.CurrentRow.SetValues(new object[] { item.ID, item.Name, item.Unit, soluong, _fdongia, _fdongia * _fSoluong });

                    }
                }
                #endregion
            }
        }

        private void DGV_OrderDetails_CellValueChanged(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            if (DGV_OrderDetails.CurrentCell == null)
                return;
            switch (DGV_OrderDetails.CurrentCell.ColumnIndex)
            {
                case 3:
                    
                    break;
                default: break;
            }
        }

        private void txt_Cashier_VIPCode_TextChanged(object sender, EventArgs e)
        {
            if((txt_Cashier_VIPCode as Control).Focused)
                fillVipMemberInfo();
        }

        private void fillVipMemberInfo()
        {
            if (lock_cname == false)
            {
                //TODO: Search and fill VIP Name
                current_point = 0;
                if (dictVipCodes.ContainsKey(txt_Cashier_VIPCode.Text))
                {
                    txt_Cashier_VIPName.Text = dictVipCodes[txt_Cashier_VIPCode.Text];
                }
                else
                {
                    txt_Cashier_VIPName.Text = "";
                }

                try
                {
                    //lb_phone.Text = "";
                    if((text_PhoneNum as Control).Focused == false)
                        text_PhoneNum.Text = "";
                    lb_vip.Visible = false;
                    lb_pointing_exp.Visible = false;
                    lb_card_exp.Visible = false;
                    lb_vip.Visible = false;
                    lbPoint.Visible = false;
                    is_vip = false;
                    current_point = 0;
                    Customer customer = new Customer(DBServices.accessdb, DBServices.mysqldb);
                    customer = DBServices.getCustomerByCardID(txt_Cashier_VIPCode.Text);
                    if (DateTime.Today.CompareTo(customer.expire_date) <= 0 || customer.expire_date == null)
                    {
                        if (DateTime.Today.CompareTo(customer.join_date.AddMonths(6)) <= 0)
                        {
                            lb_pointing_exp.Text = "ngày hết hạn tích điểm VIP 6T: " + customer.join_date.AddMonths(6).ToString("dd/MM/yyyy");
                        }
                        else
                        {
                            lb_pointing_exp.Text = "ngày hết hạn tích điểm VIP 12T: " + customer.join_date.AddYears(1).ToString("dd/MM/yyyy");
                        }

                        if (customer.is_vip)
                        {
                            lb_vip.Visible = true;
                            is_vip = true;
                        }

                        if (customer.discount_percent > 0)
                        {
                            txt_Cashier_DiscountPercent.Text = customer.discount_percent.ToString();
                        }
                        else
                        {
                            txt_Cashier_DiscountPercent.Text = "0";
                        }
                        lbPoint.Text = customer.point.ToString();
                        lb_bill_point.Text = "";
                        lb_card_exp.Text = "ngày hết hạn thẻ : " + customer.expire_date.ToString("dd/MM/yyyy");
                        lb_pointing_exp.Visible = true;
                        lb_card_exp.Visible = true;
                        lbPoint.Visible = true;
                        //lb_phone.Text = "SĐT : " + customer.phone;
                        if ((text_PhoneNum as Control).Focused == false)
                            text_PhoneNum.Text = customer.phone;
                        btnRenewMembership.Enabled = false;
                    }
                    else
                    {
                        lb_pointing_exp.Text = "Thẻ đã hết hạn !";
                        lb_pointing_exp.Visible = true;
                        btnRenewMembership.Enabled = true;
                    }
                }
                catch (Exception ex) { }

            }
        }

        private void DGV_OrderDetails_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            //TODO: Calculate from DGV_OrderDetails
            CalculateAll();
        }
        
        private void DGV_table_SelectionChanged(object sender, EventArgs e)
        {
            DGV_OrderDetails.Rows.Clear();
            
            if (DGV_table.SelectedRows.Count > 0)
            {
                try
                {
                    label_current_table.Text = DGV_table.SelectedRows[0].Cells[1].Value.ToString();
                    current_table_index = DGV_table.SelectedRows[0].Index;
                    int selectedTableId = int.Parse(DGV_table.SelectedRows[0].Cells[0].Value.ToString());
                    if (ordersList.ContainsKey(selectedTableId))
                    {
                        txtCongTy.Text = ordersList[selectedTableId].Company;
                        combo_Cashier_PhucVu.Text = ordersList[selectedTableId].Waiter;
                        txtSoKhach.Text = ordersList[selectedTableId].CustomerCount;
                        txt_Cashier_VIPCode.Text = ordersList[selectedTableId].VIPCode;
                        txt_Cashier_VIPName.Text = ordersList[selectedTableId].VIPName;
                        lb_bill_point.Text = ordersList[selectedTableId].bill_point;
                        if (ordersList[selectedTableId].show_discount_ticket != "")
                        {
                            lb_dis_ticket.Text = ordersList[selectedTableId].show_discount_ticket;
                            lb_dis_ticket.Visible = true;
                        }
                        else
                        {
                            lb_dis_ticket.Text = "";
                            lb_dis_ticket.Visible = false;
                        }
                        combo_Cashier_PaymentMethod.Text = ordersList[selectedTableId].PaymentMethod;
                        txtCongTy.Text = ordersList[selectedTableId].Company;
                        txt_Cashier_DiscountPercent.Text = ordersList[selectedTableId].DiscountP;
                        lbPoint.Text = ordersList[selectedTableId].Point;
                        if (ordersList[selectedTableId].OrderEntry.Count > 0)
                        {
                            foreach (OrderDetailsRecord record in ordersList[selectedTableId].OrderEntry)
                            {
                                DGV_OrderDetails.Rows.Add(new string[] { 
                            record.MaMon,
                            record.TenMon,
                            record.DVT,
                            record.SoLuong,
                            record.DonGia,
                            record.ThanhTien,
                        });
                            }
                        }
                    }
                    else
                    {
                        txtCongTy.Text = "";
                        combo_Cashier_PhucVu.Text = "";
                        txtSoKhach.Text = "";
                        txt_Cashier_VIPCode.Text = "";
                        txt_Cashier_VIPName.Text = "";
                        combo_Cashier_PaymentMethod.Text = "";
                        txtCongTy.Text = "";
                        txt_Cashier_DiscountPercent.Text = "0";
                        lbPoint.Text = "0";
                        lb_dis_ticket.Text = "";
                        lb_bill_point.Text = "";
                    }
                    CalculateAll();
                }
                catch { }
            }            
        }
        
        private void DGV_table_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            try
            {
                //int tableId = int.Parse(DGV_table.Rows[e.Row.Index].Cells[0].Value.ToString());
                //VertTable.Add(tableId.ToString());
                //if (VertTable.Count >= 2)
                //{
                //    SaveOrders(int.Parse(VertTable[1])); 
                //    VertTable.Clear();
                //}
            }
            catch { VertTable.Clear(); }
        }

        private void txt_Cashier_DiscountPercent_TextChanged(object sender, EventArgs e)
        {
            CalculateAll();
        }
        private void txt_Cashier_Total_TextChanged(object sender, EventArgs e)
        {
            CalculateAll();
        }

        #endregion End of: Events - User actions

        #region Helper Methods

        /// <summary>
        /// Delegate function callback
        /// </summary>
        /// <param name="data">Returned data</param>
        private void FillRecievedData(ItemEntry data)
        {
            foreach (DataGridViewRow row in DGV_OrderDetails.Rows)
            {
                if (row.Cells["clMaMon"].Value != null)
                {
                    if (row.Cells["clMaMon"].Value.ToString() == "/")
                    {
                        row.SetValues(new object[] { data.ID, data.Name, data.Unit, "1", data.Price, data.Price });
                        //TODO: Calculate from DGV_OrderDetails
                        CalculateAll();
                        return;
                    }
                }
                else if (row.Cells["clTenMon"].Value != null)
                {
                    if (row.Cells["clTenMon"].Value.ToString() == "/")
                    {
                        row.SetValues(new object[] { data.ID, data.Name, data.Unit, "1", data.Price, data.Price });
                        //TODO: Calculate from DGV_OrderDetails
                        CalculateAll();
                        return;
                    }
                }
            }
            

        }

        /// <summary>
        /// Save the order details to Dictionary by tableId
        /// </summary>
        /// <param name="tableId"></param>
        private void SaveOrders(int tableId)
        {
            try
            {
                OrderDetailsEntry orderInfo = new OrderDetailsEntry();
                orderInfo.TabelId = tableId;
                orderInfo.Waiter = combo_Cashier_PhucVu.Text;
                orderInfo.CashierName = "";
                orderInfo.Company = txtCongTy.Text;
                orderInfo.CustomerCount = txtSoKhach.Text;
                orderInfo.PaymentMethod = combo_Cashier_PaymentMethod.Text;
                orderInfo.Point = lbPoint.Text;
                orderInfo.VIPCode = txt_Cashier_VIPCode.Text;
                orderInfo.DiscountP = txt_Cashier_DiscountPercent.Text;
                orderInfo.VIPName = txt_Cashier_VIPName.Text;
                orderInfo.Point = lbPoint.Text;
                orderInfo.show_discount_ticket = lb_dis_ticket.Text;
                orderInfo.bill_point = lb_bill_point.Text;
                

                List<OrderDetailsRecord> records = new List<OrderDetailsRecord>();
                foreach (DataGridViewRow row in DGV_OrderDetails.Rows)
                {
                    if (row.Index < DGV_OrderDetails.Rows.Count - 1 && row.Cells[0].Value!=null)
                    {
                        records.Add(new OrderDetailsRecord()
                        {
                            MaMon = row.Cells["clMaMon"].Value.ToString(),
                            TenMon = row.Cells["clTenMon"].Value.ToString(),
                            DVT = row.Cells["clDVT"].Value.ToString(),
                            SoLuong = row.Cells["clSoLuong"].Value.ToString(),
                            DonGia = row.Cells["clDonGia"].Value.ToString(),
                            ThanhTien = row.Cells["clThanhTien"].Value.ToString(),
                        });
                        DGV_table.Rows[current_table_index].DefaultCellStyle.BackColor = Color.Yellow;
                    }
                }
                orderInfo.OrderEntry = records;
                if (!ordersList.ContainsKey(tableId))
                {
                    ordersList.Add(tableId, orderInfo);
                    
                }
                else
                {
                    ordersList[tableId] = orderInfo;
                }
                
            }
            catch { }
        }
        private void ClearOrders()
        {
            try
            {
                DGV_table.Rows[current_table_index].DefaultCellStyle.BackColor = Color.White;
                combo_Cashier_PhucVu.Text = "";
                txtCongTy.Text = "";
                txtSoKhach.Text="";
                combo_Cashier_PaymentMethod.Text="";
                lbPoint.Text="";
                txt_Cashier_VIPCode.Text="";
                txt_Cashier_VIPName.Text="";
                txt_Cashier_DiscountPercent.Text = "0";
                lb_bill_point.Text = "";
                lb_dis_ticket.Text = "";
                DGV_OrderDetails.DataSource = null;
                DGV_OrderDetails.Rows.Clear();
                DGV_OrderDetails.Refresh();
            }
            catch { }
           
        }

        private void CalculateAll()
        {
            float totalBaseAll = Totals;
            txt_Cashier_Total.Text = totalBaseAll.ToString();            
            float discountPercents = float.TryParse(txt_Cashier_DiscountPercent.Text, out discountPercents) ? discountPercents : 0f;
            float discountValue = discountPercents * totalBaseAll / 100f;
            txt_Cashier_Discount.Text = discountValue.ToString();
            txt_Cashier_VAT.Text = ((totalBaseAll - discountValue) * VAT).ToString();
            txt_Cashier_Charge.Text = (totalBaseAll + float.Parse(txt_Cashier_VAT.Text) - discountValue).ToString();
        }

        #endregion

        #region Override methods

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {            
            if(keyData==Keys.F2)
            {
                ThanhToan();
                return true;
            }
            else if (keyData == Keys.F5)
            {
                Print();
                return true;
            }
            else if (keyData == Keys.F6)
            {
                //TimTheVIP();
                return true;
            }
            else if (keyData == Keys.F7)
            {
                QLKH();
                return true;
            }
            else if (keyData == Keys.F10)
            {
                KetThuc();
                //return true;
            }
            else if (keyData == (Keys.Control | Keys.T))
            {
                TimBan();
                return true;
            }
            else if (keyData == (Keys.Control | Keys.M))
            {
                Member();
                return true;
            }
            else if (keyData == (Keys.Control | Keys.L))
            {
                Member2();
                return true;
            }
            else if (keyData == (Keys.Control | Keys.W))
            {
                TimPhucVu();
                return true;
            }
            else if (keyData == (Keys.Control | Keys.O))
            {
                FocusDGVOrderDetail();
                return true;
            }

            else if (keyData == (Keys.Control | Keys.D))
            {
                ChiecKhau();
                return true;
            }
            else if (keyData == (Keys.Control | Keys.V))
            {
                CheckVAT();
                return true;
            }
            else if (keyData == (Keys.Control | Keys.R))
            {
                get_member_info();
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);

        }

        #endregion

        #region Shortcut key methods

        private void Print()
        {
            lb_dis_ticket.Text = "";

            //get bill template
            string printBill = PrintBillTemplate;

            //parse bill info
            printBill = printBill.Replace("<%OrderDT%>", String.Format("{0:M/d/yyyy}", DateTime.Now) + "&nbsp;&nbsp;&nbsp;&nbsp;" + DateTime.Now.ToString("HH:mm"));
            printBill = printBill.Replace("<%TableId%>", DGV_table.Rows[SelectedTableId-1].Cells[1].Value.ToString()); 
            printBill = printBill.Replace("<%Waiter%>", combo_Cashier_PhucVu.Text);
            printBill = printBill.Replace("<%CustCount%>", txtSoKhach.Text);
            printBill = printBill.Replace("<%ListItems%>", ListItemHTMLString);

            int discount_percent = int.Parse(txt_Cashier_DiscountPercent.Text);

            if (discount_percent==0)
            {
                printBill = printBill.Replace("<%status%>", "nodisplay");
            
            }
            float VAT = float.Parse(txt_Cashier_VAT.Text.ToString());

            if (VAT == 0)
            {
                printBill = printBill.Replace("<%VAT_status%>", "nodisplay");

            }

            float total_bill = Totals - float.Parse(txt_Cashier_Discount.Text);

            if (txt_Cashier_VIPCode.Text == "" || txt_Cashier_VIPName.Text == "")
            {
                printBill = printBill.Replace("<%member_status%>", "nodisplay");

            }
            else
            {
                Customer customer = new Customer(DBServices.accessdb,DBServices.mysqldb);
                customer = DBServices.getCustomerByCardID(txt_Cashier_VIPCode.Text);

                //check birhday
                if (DateTime.Equals(customer.birthday,DateTime.MinValue))
                {
                    System.TimeSpan diff = customer.birthday.Subtract(DateTime.Now);
                    if (diff.Days <= 7 && (customer.birthday.Month - DateTime.Now.Month <= 1))
                    {
                        lb_dis_ticket.Text += "\nChúc mừng sinh nhật !";
                        lb_dis_ticket.Visible = true;
                    }
                }

                //check expired
                DateTime expired_date = customer.join_date.AddYears(1);
                string str_expired_date = String.Format("{0:MM/dd/yyyy}", expired_date);
                int bill_point = (int)(total_bill / 50000);
                int after_bill_point = bill_point + customer.point;
                int max_discount_tickets = (int)((360 - customer.point) / 60);

                //check give discount ticket
                if (!customer.is_vip)
                {
                    int discount_tickets = (int)(((customer.point % 60) + bill_point) / 60);
                    if (max_discount_tickets > 0)
                    {
                        if (discount_tickets > max_discount_tickets)
                        {
                            discount_tickets = max_discount_tickets;
                        }
                        if (discount_tickets > 0)
                        {
                            lb_dis_ticket.Text = "Earn " + discount_tickets.ToString() + " Discount 10% Ticket(s)";
                        }
                        lb_dis_ticket.Visible = true;
                    }
                    
                }

                //ADD POINT=============
                string card_id = txt_Cashier_VIPCode.Text;
                if (card_id != "")
                {
                    DBServices.AddPoint(card_id, bill_point);
                }

                // render data to template
                lb_bill_point.Text = bill_point.ToString();
                printBill = printBill.Replace("<%Customer_name%>", txt_Cashier_VIPName.Text);
                printBill = printBill.Replace("<%Card_id%>", txt_Cashier_VIPCode.Text);
                printBill = printBill.Replace("<%Point%>", after_bill_point.ToString());
                printBill = printBill.Replace("<%Expired_date%>", str_expired_date);
            }
            
            //redner data to template
            printBill = printBill.Replace("<%SubTotal%>", Totals.ToString("0,0"));
            printBill = printBill.Replace("<%Discount%>", float.Parse(txt_Cashier_Discount.Text).ToString("0,0"));
            printBill = printBill.Replace("<%Discount_Percent%>", discount_percent.ToString());
            printBill = printBill.Replace("<%Total%>", total_bill.ToString("0,0"));
            printBill = printBill.Replace("<%VAT%>", float.Parse(txt_Cashier_VAT.Text).ToString("0,0"));
            printBill = printBill.Replace("<%Cash%>", float.Parse(txt_Cashier_Charge.Text).ToString("0,0"));

            //parse html to browserprint
       
            browserPrint.DocumentText = printBill;
        }


        private bool is_birthday(DateTime birthday)
        {
            DateTime today = new DateTime();
            today = DateTime.Now;
            if (today.Month == birthday.Month)
            {
                return true;
            }
            return false;
        }

        private void ThanhToan()
        {
            try
            {
                if (MessageBox.Show("Are you sure ?", "Check ?",MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    int tableId = int.Parse(DGV_table.Rows[current_table_index].Cells[0].Value.ToString());
                    ClearOrders();
                }
            }
            catch { VertTable.Clear(); }
        }

        private void QLKH()
        {
            customer_form customer_frm = new customer_form();
            customer_frm.sourceVipCode = txt_Cashier_VIPCode.AutoCompleteCustomSource;
            customer_frm.sourceVipName = txt_Cashier_VIPName.AutoCompleteCustomSource;
            customer_frm.ShowDialog();
        }

        private void KetThuc()
        {
                Application.Exit();
        }

        private void TimBan()
        {
            txt_SearchTable.Text = "";
            txt_SearchTable.Select();

        }

        private void Member()
        {
            txt_Cashier_VIPName.Select();

        }

        private void Member2()
        {
            txt_Cashier_VIPCode.Select();
            //txt_Cashier_VIPName.Select();

        }

        private void ChiecKhau()
        {
   
            txt_Cashier_DiscountPercent.Select();

        }

        private void TimPhucVu()
        {

            combo_Cashier_PhucVu.Select();
            combo_Cashier_PhucVu.DroppedDown = true;

        }

        private void CheckVAT()
        {
            if (check_box_VAT.CheckState == CheckState.Unchecked)
            {
                check_box_VAT.CheckState = CheckState.Checked;
            }
            else
            {
                check_box_VAT.CheckState = CheckState.Unchecked;
            }
        }

        private void FocusDGVOrderDetail()
        {
            DGV_OrderDetails.Select();
            DGV_OrderDetails.CurrentCell = DGV_OrderDetails.Rows[DGV_OrderDetails.RowCount - 1].Cells[1];
        }


        private void btnPrint_Click(object sender, EventArgs e)
        {
            Print();
        }

        private void btnThanhToan_Click(object sender, EventArgs e)
        {
            ThanhToan();
        }

        private void btnTimTheVIP_Click(object sender, EventArgs e)
        {
            AddCustomer Addcustomer_frm = new AddCustomer();
            Addcustomer_frm.ShowDialog();
        }

        private void btnQLKH_Click(object sender, EventArgs e)
        {
            QLKH();
        }

        private void btnKetThuc_Click(object sender, EventArgs e)
        {
            KetThuc();
        }

        #endregion

        private void browserPrint_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                string filename;
                filename = DGV_table.Rows[current_table_index].Cells[0].Value.ToString() + "_";
                filename += combo_Cashier_PhucVu.Text + "_";
                filename += String.Format("{0:M-d-yyyy}", DateTime.Now) + "_" + DateTime.Now.ToString("HH-mm-ss");
                filename += ".html";
                string path = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "//bill//" + filename;
                //File.WriteAllText(path, browserPrint.Document.Body.Parent.OuterHtml, Encoding.GetEncoding(browserPrint.Document.Encoding));
                browserPrint.ShowPrintPreviewDialog();
            }
            catch { }
           
        }

        private Thread UpdateThread;

        private void cashier_form_Load(object sender, EventArgs e)
        {
            btnRenewMembership.Enabled = false;
            check_box_VAT.Checked = true;
            foreach (DataGridViewColumn column in DGV_table.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            foreach (DataGridViewColumn column in DGV_OrderDetails.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            bgwSync.RunWorkerAsync();
        }


        private void DGV_OrderDetails_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
           
        }

        private void DGV_OrderDetails_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                txt_Cashier_Total.Text = this.Totals.ToString();
            }
            catch { }

        }

       

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void DGV_OrderDetails_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                try
                {
                    DGV_OrderDetails.Rows.RemoveAt(DGV_OrderDetails.CurrentCell.RowIndex);
                }
                catch { }
            }
            //else if (e.KeyCode == Keys.Enter)
            //{
            //    DGV_OrderDetails.Rows[DGV_OrderDetails.CurrentRow.Index].Cells[3].Selected = true;
            //}
        }

        private void check_box_VAT_CheckStateChanged(object sender, EventArgs e)
        {
            if (check_box_VAT.CheckState == CheckState.Checked)
            {
                // MessageBox.Show("VAT");
                VAT = 0.1f;
                CalculateAll();

            }
            else
            {
                VAT = 0f;
                CalculateAll();
            }
        }

        private void DGV_table_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int tableId = int.Parse(DGV_table.Rows[e.RowIndex].Cells[0].Value.ToString());
                SaveOrders(tableId);
            }
            catch { VertTable.Clear(); }
        }

        private void txt_Cashier_VIPName_TextChanged(object sender, EventArgs e)
        {
            /*if ((txt_Cashier_VIPName as Control).Focused)
            {
                if (lock_ccode == false)
                {
                    try
                    {
                        string str_key_of_val = "";

                        //TODO: Search and fill VIP Name
                        if (dictVipCodes.ContainsValue(txt_Cashier_VIPName.Text))
                        {
                            foreach (KeyValuePair<string, string> vipCode in dictVipCodes)
                            {
                                if (vipCode.Value == txt_Cashier_VIPName.Text)
                                {

                                    str_key_of_val = vipCode.Key;
                                }
                            }

                        }

                        txt_Cashier_VIPCode.Text = str_key_of_val;

                        //TODO: Search and fill Discount percents
                        //if (dictDiscountByVIPCodes.ContainsKey(txt_Cashier_VIPCode.Text))
                        //    txt_Cashier_DiscountPercent.Text = dictDiscountByVIPCodes[txt_Cashier_VIPCode.Text];
                        //else
                        //    txt_Cashier_DiscountPercent.Text = "";
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }*/
        }

        private void txt_Cashier_VIPCode_Enter(object sender, EventArgs e)
        {
            //if (need_get_member_info)
            //{
            get_member_info();
            //}
        }

        private void get_member_info()
        {
            if (txt_Cashier_VIPCode.Text=="")
            {
                using (DatabaseServices service = new DatabaseServices())
                {
                    AutoCompleteStringCollection _VIPCode = new AutoCompleteStringCollection();
                    AutoCompleteStringCollection _VIPName = new AutoCompleteStringCollection();
                    dictVipCodes = service.GetVIPCodes();
                    foreach (KeyValuePair<string, string> vipCode in dictVipCodes)
                    {

                        _VIPCode.Add(vipCode.Key.ToString());
                        _VIPName.Add(vipCode.Value.ToString());
                    }
                    this.txt_Cashier_VIPCode.AutoCompleteCustomSource = _VIPCode;
                    this.txt_Cashier_VIPName.AutoCompleteCustomSource = _VIPName;
                }
            }
        }

        private void txt_Cashier_VIPName_Enter(object sender, EventArgs e)
        {
            //if (need_get_member_info)
            //{
            //    get_member_info();
            //}
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        //private Dictionary<string, string> get_member_info(int card_id)
        //{
        //    return DBServices.member_info(card_id);
        //}

        private void combo_Cashier_PhucVu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                txtSoKhach.Select();
            }
        }

        private void txtSoKhach_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                combo_Cashier_PaymentMethod.Select();
                combo_Cashier_PaymentMethod.DroppedDown = true;
            }
        }

        private void combo_Cashier_PaymentMethod_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                
                txt_Cashier_VIPCode.Select();
                get_member_info();
            }
        }

        private void txt_Cashier_VIPCode_KeyDown(object sender, KeyEventArgs e)
        {
            lock_ccode = true;
            lock_cname = false;
            if (e.KeyCode == Keys.Enter)
            {
                if (txt_Cashier_VIPCode.Text != "" && txt_Cashier_VIPName.Text!="")
                {
                    FocusDGVOrderDetail();
                }
                else
                {
                    txt_Cashier_VIPName.Select();
                    get_member_info();
                }
            }
        }

        private void txt_Cashier_VIPName_KeyDown(object sender, KeyEventArgs e)
        {
            lock_ccode = false;
            lock_cname = true;

            if (e.KeyCode == Keys.Enter)
            {
                if ((txt_Cashier_VIPName as Control).Focused)
                {
                    if (lock_ccode == false)
                    {
                        try
                        {
                            string str_key_of_val = "";

                            //TODO: Search and fill VIP Name
                            if (dictVipCodes.ContainsValue(txt_Cashier_VIPName.Text))
                            {
                                foreach (KeyValuePair<string, string> vipCode in dictVipCodes)
                                {
                                    if (vipCode.Value == txt_Cashier_VIPName.Text)
                                    {

                                        str_key_of_val = vipCode.Key;
                                    }
                                }

                            }

                            txt_Cashier_VIPCode.Text = str_key_of_val;

                            //TODO: Search and fill Discount percents
                            //if (dictDiscountByVIPCodes.ContainsKey(txt_Cashier_VIPCode.Text))
                            //    txt_Cashier_DiscountPercent.Text = dictDiscountByVIPCodes[txt_Cashier_VIPCode.Text];
                            //else
                            //    txt_Cashier_DiscountPercent.Text = "";
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
                FocusDGVOrderDetail();

            }
            
        }

        private void bttn_get__Click(object sender, EventArgs e)
        {
            get_member_info();
        }

        private void txt_SearchTable_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) {
                try
                {
                    SaveOrders(DGV_table.SelectedRows[0].Index + 1);
                    //MessageBox.Show(DGV_table.SelectedRows[0].Index.ToString());
                    foreach (DataGridViewRow row in DGV_table.Rows)
                    {
                        if (row.Cells[1].Value.ToString() == txt_SearchTable.Text.ToLower() || row.Cells[1].Value.ToString() == txt_SearchTable.Text.ToUpper())
                        {
                            row.Selected = true;
                            //DGV_table.CurrentRow
                            //MessageBox.Show(DGV_table.SelectedRows[0].Index.ToString());
                            current_table_index = DGV_table.SelectedRows[0].Index;
                            //DataGridView.FirstDisplayedScrollingRowIndex;
                            DGV_table.FirstDisplayedScrollingRowIndex = current_table_index;
                            txt_SearchTable.BackColor = Color.White;

                            return;
                        }
                    }
                    txt_SearchTable.BackColor = Color.Yellow;
                }
                catch
                {
                    MessageBox.Show("Table not found.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txt_SearchTable.Text = "";
                }
            
            
            }
        }

        private void bgwSync_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                System.Threading.Thread.Sleep(DelayTime);
                SyncData();
                       
            }
            
        }

        private void bgwSync_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void bgwSync_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            
        }

        public void SyncData() 
        {
            if (DBServices.PushLog())
            {
                try
                {
                    lbUpdateLog.Invoke(new Action(() => lbUpdateLog.Text = DateTime.Now.ToString()));
                }
                catch (Exception ex)
                {
                }
            }
            if (DBServices.UpdateServer())
            {
                try
                {
                    lbUpdateServer.Invoke(new Action(() => lbUpdateServer.Text = DateTime.Now.ToString()));
                }
                catch (Exception ex)
                {
                }
            }
            if (DBServices.PullData())
            {
                try
                {
                    lbUpdateLocal.Invoke(new Action(() => lbUpdateLocal.Text = DateTime.Now.ToString()));
                }
                catch (Exception ex)
                {
                }
            }
        }

        private void btnRenewMembership_Click(object sender, EventArgs e)
        {
            try
            {
                string card_id = txt_Cashier_VIPCode.Text; 
                LOG CusLog = new LOG(DBServices.accessdb, DBServices.mysqldb);
                CusLog.customer.getCustomerLocalByCardID(card_id);
                if (CusLog.customer.RenewMembership())
                {
                    if (CusLog.RenewMembershipLogLocal())
                    {
                        MessageBox.Show("Renew membership successfully !");
                        txt_Cashier_VIPCode.Text = "";
                        txt_Cashier_VIPCode.Text = card_id;
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void text_PhoneNum_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void text_PhoneNum_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if ((text_PhoneNum as Control).Focused)
                {
                    if (text_PhoneNum.Text != "" && dicPhoneList.ContainsKey(text_PhoneNum.Text))
                    {
                        txt_Cashier_VIPCode.Text = dicPhoneList[text_PhoneNum.Text];
                        fillVipMemberInfo();
                    }
                }
            }
        }


    }
}
